package com.xzr.demo.mqserver;

import com.xzr.demo.common.*;
import com.xzr.demo.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个 BrokerServer 就是咱们消息队列 本体服务器
 * 本质上就是一个TCP 的服务器
 *
 * @Author：徐志荣
 * @Date：2023/8/17 下午 4:02
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;
    //当前考虑一个 Broker Server 上只能有一个虚拟机
    private VirtualHost virtualHost = new VirtualHost("default");
    //哪些客户端正在和咱们的服务器在通信
    // 此处的key 是channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<String, Socket>();
    //引入一个线程池，来处理多个客户端的请求
    private ExecutorService executorService = null;
    //引入一个 boolean 变量控制服务器是否能继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动！");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑丢给这个线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行");
        }

    }

    /**
     * 一般来说停止服务器，就是直接 kill 掉对应进程就行了
     * 此处，还是搞一个单独的停止方法，主要是用于后续的单元测试
     *
     * @return
     */
    public void stop() throws IOException {
        runnable = false;
        //把线程池中的任务放弃，让线程都销毁
        executorService.shutdownNow();
        serverSocket.close();
    }

    /**
     * 通过这个方法，来处理一个客户端的连接
     * 在这一个连接中，可能会涉及到多个请求和响应
     *
     * @param clientSocket
     * @return
     */
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //这里需要按照特定格式来读取并解析，此时就需要用 DataInputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1. 读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3. 把响应写回给客户端
                    writeResponse(dataOutputStream, response);
                }
            } catch (EOFException | SocketException e) {
                //结束的时候 会抛出 EOFException 异常
                //需要借助这个异常来结束循环
                System.out.println("[BrokerServer] Connection关闭！ 客户端的地址：" + clientSocket.getInetAddress().toString()
                        + ":" + clientSocket.getPort());
            }
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] Connection异常！");
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                //把 socket对应的channel 也要关闭
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 读取
     *
     * @param dataInputStream
     * @return
     */
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }


    /**
     * 返回响应
     *
     * @param dataOutputStream
     * @param response
     * @return
     */
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //刷新缓存区
        dataOutputStream.flush();
    }

    /**
     * 根据请求计算响应
     * <p>
     * 此处，设定的类，父类是 BasicArguments
     * <p>
     * 0x1 创建 channel
     * • 0x2 关闭 channel
     * • 0x3 创建 exchange
     * • 0x4 销毁 exchange
     * • 0x5 创建 queue
     * • 0x6 销毁 queue
     * • 0x7 创建 binding
     * • 0x8 销毁 binding
     * • 0x9 发送 message
     * • 0xa 订阅 message
     * • 0xb 返回 ack
     * • 0xc 服务器给客⼾端推送的消息. (被订阅的消息) 响应独有的.
     *
     * @param request
     * @param clientSocket
     * @return
     */
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        //1.把 request 中的payload 做一个初步的诊断
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());

        System.out.println("[Request] rid = " + basicArguments.getRid() + ",channelId = " + basicArguments.getChannelId()
                + ", type: " + request.getType() + ",length = " + request.getLength());
        boolean ok = true;
        //2. 根据 type 的值，来进一步区分要干啥？
        if (request.getType() == 0x1) {
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel 完成，channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel 完成，channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(), arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());

        } else if (request.getType() == 0x5) {
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(),
                    arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());

        } else if (request.getType() == 0x7) {
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());

        } else if (request.getType() == 0x8) {
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnBind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());

        } else if (request.getType() == 0xa) {
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        //这个回调函数，要做的工作就是把服务器收到的消息可以直接推送回对应的消费者客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            //先知道当前这个收到的消息，要发给那个客户端
                            //此处的ConsumerTag ，其实就是 ChannelId，
                            //ChannelId 去sessions 中查询 ->socket对象，从来发送数据了
                            //1. 根据channelId 找到 socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭！");

                            }
                            //2.构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(consumerTag);
                            subScribeReturns.setRid(""); //这里还有响应，不设置也没关系
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);

                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            // Payload 就是一个 SubScribeReturns对象
                            response.setPayload(payload);
                            //3. 把数据写回给客户端
                            // 此处的 DataOutputStream 不能close
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);

                        }
                    });

        } else if (request.getType() == 0xb) {
            //调用basicAck 确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());

        } else {
            //当前的type 是非法的
            throw new MqException("[BrokerServer] 未知的type！ type = " + request.getType());

        }
        //3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);

        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[BrokerServer] rid = " + basicReturns.getRid() + ",channelId =  " + basicArguments.getChannelId()
                + ", type = " + response.getType() + ",length = " + request.getLength());

        return response;
    }


    /**
     * 主要就是 遍历上述的sessions hash表，把该被关闭的 socket对应的键值对，统统删掉
     * 实现清理过期的会话
     *
     * @param clientSocket
     * @return
     */
    private void clearClosedSession(Socket clientSocket) {
        //1.遍历hash表
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                //不能直接删除
                //这是属于集合类的一个大忌，一边遍历，一边删除
                //sessions.remove(entry.getKey());
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session 完成，被清理的channelId = " + toDeleteChannelId);
    }
}
